package cn.com.vrv.service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cn.com.vrv.entity.QueryObj;
import cn.com.vrv.entity.RecognitionTask;
import cn.com.vrv.mapper.RecognitionTaskMapper;
import cn.com.vrv.util.Configure;
import cn.com.vrv.util.StringUtils;
/**
 * <一句话功能简述>
 * 
 * @author 赵炎
 * @version [V1.00, 2017年11月21日]
 * @see [相关类/方法]
 * @since V1.00
 */
@Service
public class RecognitionTaskService
{
    @Autowired
    private RecognitionTaskMapper recognitionTaskMapper;
    
    @Value("${upload.path}")
    private String path;//配置文件上传路径
    /**
     * 查询全部任务列表
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    public Page<RecognitionTask> findAll(Pageable pageable)
    {
        return this.recognitionTaskMapper.findAll(pageable);
    }
    
    
    public Page<RecognitionTask> findBookCriteria(Integer page, Integer size, final QueryObj obj) {  
        Pageable pageable = new PageRequest(page, size, Sort.Direction.ASC, "createTime");  
        Page<RecognitionTask> bookPage = this.recognitionTaskMapper.findAll(new Specification<RecognitionTask>(){  
        	 @Override
             public javax.persistence.criteria.Predicate toPredicate(Root<RecognitionTask> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                 Path<String> namePath = root.get("fileName");
                 Path<String> taskType = root.get("taskType");
                 /**
                  * 连接查询条件, 不定参数，可以连接0..N个查询条件
                  */
                 if(StringUtils.isNotBlank(obj.getFileName())&&StringUtils.isNotBlank(obj.getTaskType()))
                 {
                	 query.where(cb.like(namePath, "%" + obj.getFileName() + "%"),cb.like(taskType, "%" + obj.getTaskType() + "%")); //这里可以设置任意条查询条件
                	 return null;
                 }
                 if(StringUtils.isNotBlank(obj.getTaskType()))
                 {
                	 query.where(cb.like(taskType, "%" + obj.getTaskType() + "%")); //这里可以设置任意条查询条件
                	 return null;
                 }
                 if(StringUtils.isNotBlank(obj.getFileName()))
                 {
                	 query.where(cb.like(namePath, "%" + obj.getFileName() + "%")); //这里可以设置任意条查询条件
                	 return null;
                 }
                 if(StringUtils.isBlank(obj.getFileName())&&StringUtils.isBlank(obj.getTaskType()))
                 {
                	 query.where(); //这里可以设置任意条查询条件
                	 return null;
                 }
                 
                 return null;
             }  
        },pageable);  
        return bookPage;  
    }
    
    
    public RecognitionTask save(RecognitionTask task)
    {
        
        return this.recognitionTaskMapper.save(task);
    }
    
    public RecognitionTask findByTaskId(String taskId)
    {
        
        return this.recognitionTaskMapper.findByTaskId(new Long(taskId));
    }
    
    public void deleteByTaskId(String taskId)
    {
    	 this.recognitionTaskMapper.deleteByTaskId(new Long(taskId));
    }
    
    public void updateByTaskId(RecognitionTask recognitionTask)
    {
    	this.recognitionTaskMapper.updateByTaskId(recognitionTask.getFileName(), recognitionTask.getUpdateTime(), recognitionTask.getTaskType(), recognitionTask.getStatus(), recognitionTask.getTaskId());
    }
    
    
/**
 * 上传
 * @param file
 * @return
 */
	public String upload(MultipartFile file) {
		 if(file.isEmpty()){
	            return "false";
	        }
	        String fileName = file.getOriginalFilename();
	        int size = (int) file.getSize();
	        System.out.println(fileName + "-->" + size);
	       /* Configure config = new Configure("application-dev.properties");
	        
	        String path = config.getValue("upload.path");*/
	        File dest = new File(path + "/" + fileName);
	        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
	            dest.getParentFile().mkdir();
	        }
	        try {
	            file.transferTo(dest); //保存文件
	            return "true";
	        } catch (IllegalStateException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return "false";
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return "false";
	        }
		
	}
    
	/**
	 * 下载
	 * @param filename
	 * @param response
	 * @return
	 */
	   public String downLoad(String filename,HttpServletResponse response){
		   Configure config = new Configure("application-dev.properties");
	        String filePath = config.getValue("upload.path");
	        File file = new File(filePath + "/" + filename);
	        if(file.exists()){ //判断文件父目录是否存在
	            response.setContentType("application/force-download");
	            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
	            
	            byte[] buffer = new byte[1024];
	            FileInputStream fis = null; //文件输入流
	            BufferedInputStream bis = null;
	            
	            OutputStream os = null; //输出流
	            try {
	                os = response.getOutputStream();
	                fis = new FileInputStream(file); 
	                bis = new BufferedInputStream(fis);
	                int i = bis.read(buffer);
	                while(i != -1){
	                    os.write(buffer);
	                    i = bis.read(buffer);
	                }
	                
	            } catch (Exception e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }
	            System.out.println("----------file download" + filename);
	            try {
	                bis.close();
	                fis.close();
	            } catch (IOException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }
	        }
	        return "true";
	    }
	
}
